package com.douma.lock;


import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 抖码课堂，专注中国程序员基础内功修炼
 * 官网：douma-tech.com
 * 公众号：抖码课堂
 *
 * @作者 : 老汤
 */
public class TestReentrantLock {

    private static RedissonClient redissonClient;
    private static RLock lock;

    static {
        Config config = new Config();
        SingleServerConfig singleServerConfig = config.useSingleServer();
        singleServerConfig.setAddress("redis://192.168.126.131:6380");
        singleServerConfig.setPassword("123456");

        redissonClient = Redisson.create(config);
        lock = redissonClient.getLock("mylock");
    }

    public static void main(String[] args) {
        try {
            lock.tryLock(10, 1000, TimeUnit.SECONDS);

            System.out.println("do something");
            m();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

        redissonClient.shutdown();
    }

    public static void m() {
        try {
            lock.tryLock(10, 1000, TimeUnit.SECONDS);

            System.out.println("do some other thing");

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
